import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Table } from 'antd';
import * as Actions from './store/action';

class index extends Component {

  constructor(props) {
    super(props)
    this.state = {
      pagination: {
        current: 1,   // 当前页数
        pageSize: 10, // 每页大小
        total: 0     // 数据总数
      }
    }
  }

  componentDidMount() {
    this.props.pageQuery(this.state.pagination);
  }

  componentDidUpdate(nextProps) {
    const { data } = this.props;
    if (data !== nextProps.data) {
      console.log(data);
      this.setState({
        pagination: {
          current: data.current,   // 当前页数
          pageSize: data.pageSize, // 每页大小
          total: data.total    // 数据总数
        }
      })
    }
  }

  /**
   * Table改变触发的回调函数
   * @param {JSON} pagination 
   */
  handleTableChange = (pagination) => {
    console.log(pagination);
    this.setState({
      pagination: pagination
    })
    this.props.pageQuery(pagination);
  }

  render() {

    const { pagination } = this.state;

    const columns = [
      {
        title: '序号',
        dataIndex: 'key',
        key: 'key',
        align: 'center',
      },
      {
        title: '账号',
        dataIndex: 'account',
        key: 'account',
        align: 'center',
      },
      {
        title: '密码',
        dataIndex: 'password',
        key: 'password',
        align: 'center',
      },
      {
        title: '角色',
        dataIndex: 'roleName',
        key: 'roleName',
        align: 'center',
      }]
    return (
      <Table
        bordered
        columns={columns}
        pagination={pagination}
        onChange={this.handleTableChange}
        dataSource={this.props.data.data}
      />
    )
  }
}

const mapStateToProps = (state) => ({
  data: state.pageQuery.data
})

const mapDispatchToProps = (dispatch) => ({
  pageQuery(data) {
    dispatch(Actions.pageQuery(data));
  }
})

export default connect(mapStateToProps, mapDispatchToProps)(index)